package handler

import (
	"crypto/rsa"
	"encoding/base64"
	"math/big"
	"net/http"
	"project-info/src/model"

	"project-info/src/lib")

// WellKnownConfiguration OIDC发现端点
// GET /.well-known/openid_configuration
func WellKnownConfiguration(c *lib.GinContext) (err error) {
	// 从配置文件读取OIDC服务器配置信息
	oidcConfig := model.GloOIDC
	baseUrl := oidcConfig.BaseUrl
	if baseUrl == "" {
		baseUrl = oidcConfig.Issuer
	}
	
	config := map[string]interface{}{
		"issuer":                                oidcConfig.Issuer,
		"authorization_endpoint":                baseUrl + "/oidc/auth",
		"token_endpoint":                        baseUrl + "/oidc/token",
		"userinfo_endpoint":                     baseUrl + "/oidc/userinfo",
		"jwks_uri":                              baseUrl + "/oidc/jwks",
		"end_session_endpoint":                  baseUrl + "/oidc/logout",
		"revocation_endpoint":                   baseUrl + "/oidc/revoke",
		"introspection_endpoint":                baseUrl + "/oidc/introspect",
		"response_types_supported":              oidcConfig.SupportedResponseTypes,
		"grant_types_supported":                 oidcConfig.SupportedGrantTypes,
		"subject_types_supported":               []string{"public"},
		"id_token_signing_alg_values_supported": []string{oidcConfig.SigningAlgorithm},
		"scopes_supported":                      oidcConfig.DefaultScopes,
		"token_endpoint_auth_methods_supported": []string{"client_secret_basic", "client_secret_post", "none"},
		"claims_supported":                      []string{"sub", "name", "preferred_username", "roles", "permissions"},
		"code_challenge_methods_supported":      []string{"plain", "S256"},
	}

	return c.JSON(http.StatusOK, config)
}

// JWKS OIDC JWKS端点
// GET /oidc/jwks
func JWKS(c *lib.GinContext) (err error) {
	// 获取真实的RSA公钥
	publicKey := getRSAPublicKey()
	
	// 将RSA公钥转换为JWK格式
	n := base64.RawURLEncoding.EncodeToString(publicKey.N.Bytes())
	e := base64.RawURLEncoding.EncodeToString(big.NewInt(int64(publicKey.E)).Bytes())
	
	// 从配置文件读取密钥配置
	oidcConfig := model.GloOIDC
	
	jwks := map[string]interface{}{
		"keys": []map[string]interface{}{
			{
				"kty": "RSA",
				"use": "sig",
				"kid": oidcConfig.KeyId,
				"alg": oidcConfig.SigningAlgorithm,
				"n":   n,
				"e":   e,
			},
		},
	}

	return c.JSON(http.StatusOK, jwks)
}

// getRSAPublicKey 获取RSA公钥（从token.go中获取）
func getRSAPublicKey() *rsa.PublicKey {
	// 调用token.go中的公开函数获取RSA公钥
	return GetRSAPublicKey()
}
